<script setup lang="ts">
import { computed, h, onMounted, reactive, ref } from 'vue';
import { NButton, NForm, NFormItem, NInput, useDialog, useMessage } from 'naive-ui';
import { VueDraggableNext as Draggable } from 'vue-draggable-next';
import { InventoryGoods } from '@/service/api/inventory';
import { useAuthStore } from '@/store/modules/auth';
import SvgIcon from '@/components/custom/svg-icon.vue';

interface GoodsClass {
  objectId: string;
  content: string;
  createdAt: string;
  goodClassObjectId?: string;
  children?: GoodsClass[];
  key?: number;
  goodClasses?: GoodsClass[];
  hasChildren?: boolean;
  expanded?: boolean; // 展开状态
}

// 状态管理
const message = useMessage();
const dialog = useDialog();
const authStore = useAuthStore();
const loading = ref(false);
const classList = ref<GoodsClass[]>([]);

// 表单数据
const formData = reactive({
  objectId: '',
  content: '',
  goodClassObjectId: '',
  classIds: [] as string[]
});

// 权限检查
const rights = computed(() => authStore.getInventoryRights());
const canAdd = computed(() => rights.value?.category?.modify ?? false);
const canModify = computed(() => rights.value?.category?.modify ?? false);
const canRemove = computed(() => rights.value?.category?.remove ?? false);

// 日期格式化函数
const formatDate = (dateStr: string) => {
  return $dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss');
};

// 移除未使用的 DataTableColumns 配置

// VueDraggableNext拖拽事件处理
const handleDragEnd = async (evt: any) => {
  if (!canModify.value) {
    message.error('暂无排序权限');
    await fetchClassList(); // 恢复原始顺序
    return;
  }

  const { oldIndex, newIndex } = evt;
  if (oldIndex === newIndex) return;

  const movedItem = classList.value[newIndex];
  const targetItem = classList.value[oldIndex];

  if (!movedItem || !targetItem) return;

  try {
    const response = await InventoryGoods.upDownGoodsClass(canModify.value, {
      class1: movedItem,
      class2: targetItem
    });

    if (response && !response.error) {
      message.success('排序更新成功');
    } else {
      message.error('排序更新失败');
      await fetchClassList(); // 恢复原始顺序
    }
  } catch (error) {
    message.error('排序更新失败');
    await fetchClassList(); // 恢复原始顺序
  }
};

// 事件处理方法
const handleAddNew = () => {
  if (!canAdd.value) {
    message.error('暂无添加权限');
    return;
  }

  formData.objectId = '';
  formData.content = '';
  formData.goodClassObjectId = '';
  formData.classIds = [];

  openCategoryDialog();
};

const handleAddChild = (parentClass: GoodsClass) => {
  if (!canAdd.value) {
    message.error('暂无添加权限');
    return;
  }

  formData.objectId = '';
  formData.content = '';
  formData.goodClassObjectId = parentClass.objectId;
  formData.classIds = [parentClass.objectId];

  openCategoryDialog();
};

const handleEdit = (classItem: GoodsClass) => {
  if (!canModify.value) {
    message.error('暂无编辑权限');
    return;
  }

  formData.objectId = classItem.objectId;
  formData.content = classItem.content;
  formData.goodClassObjectId = classItem.goodClassObjectId || '';
  formData.classIds = classItem.goodClassObjectId ? [classItem.goodClassObjectId] : [];

  openCategoryDialog();
};

const handleDelete = (classItem: GoodsClass) => {
  if (!canRemove.value) {
    message.error('暂无删除权限');
    return;
  }

  window.$dialog?.warning({
    title: '确认删除',
    content: `确定要删除分类"${classItem.content}"吗？此操作不可恢复。`,
    positiveText: '确认删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      const response = await InventoryGoods.removeGoodsClass(classItem.objectId);
      if (response && !response.error) {
        message.success('删除成功');
        await fetchClassList();
      }
    }
  });
};

const handleMove = async (index: number, direction: 1 | -1) => {
  if (!canModify.value) {
    message.error('暂无移动权限');
    return;
  }

  const currentItem = classList.value[index];
  const targetIndex = direction === 1 ? index - 1 : index + 1;
  const targetItem = classList.value[targetIndex];

  if (!currentItem || !targetItem) return;

  const response = await InventoryGoods.upDownGoodsClass(canModify.value, {
    class1: currentItem,
    class2: targetItem
  });

  if (response && !response.error) {
    message.success('移动成功');
    await fetchClassList();
  }
};

const handleSave = async () => {
  if (!formData.content.trim()) {
    message.error('请填写分类名称');
    return;
  }

  const response = await InventoryGoods.saveGoodsClass(formData);
  if (response && !response.error) {
    message.success('保存成功');

    // 如果是编辑现有分类，只更新对应的分类名称，不刷新整个列表
    if (formData.objectId) {
      updateClassItemContent(formData.objectId, formData.content);
    } else {
      // 如果是新增分类，则需要刷新列表获取新数据
      await fetchClassList();
    }

    return true; // 返回true表示保存成功，useDialog会自动关闭
  }
  return false; // 返回false阻止弹窗关闭
};

const handleCancel = () => {
  formData.objectId = '';
  formData.content = '';
  formData.goodClassObjectId = '';
  formData.classIds = [];
};

// 展开/折叠切换
const toggleExpand = (record: GoodsClass) => {
  record.expanded = !record.expanded;
};

// 更新特定分类的名称（用于编辑后不刷新整个列表）
const updateClassItemContent = (objectId: string, newContent: string) => {
  const updateItem = (items: GoodsClass[]): boolean => {
    for (const item of items) {
      if (item.objectId === objectId) {
        item.content = newContent;
        return true;
      }
      // 递归检查子分类
      if (item.children && item.children.length > 0) {
        if (updateItem(item.children)) {
          return true;
        }
      }
    }
    return false;
  };

  updateItem(classList.value);
};

const openCategoryDialog = () => {
  dialog.create({
    title: '分类设置',
    content: () => h('div', { class: 'py-4' }, [
      h(NForm, { labelWidth: '80px' }, [
        h(NFormItem, { label: '分类名称', required: true }, [
          h(NInput, {
            value: formData.content,
            'onUpdate:value': (value: string) => {
              formData.content = value;
            },
            placeholder: '请填写分类名称',
            maxlength: 50,
            showCount: true
          })
        ])
      ])
    ]),
    style: { width: '500px', zIndex: '10000' },
    maskClosable: false,
    positiveText: '确认',
    negativeText: '取消',
    onPositiveClick: handleSave,
    onNegativeClick: () => {
      handleCancel();
      return true;
    }
  });
};

// 数据处理方法
const processClassData = (data: any[]): GoodsClass[] => {
  return data.map((item, index) => {
    const processedItem: GoodsClass = {
      ...item,
      key: index,
      children: item.goodClasses || [],
      expanded: true // 默认展开所有分类
    };

    // 处理子分类
    if (processedItem.children && processedItem.children.length > 0) {
      processedItem.children = processedItem.children.map((child: any, childIndex: number) => ({
        ...child,
        key: childIndex,
        children: child.goodClasses || []
      }));

      processedItem.hasChildren = true;
    }

    return processedItem;
  });
};

// 获取分类列表
const fetchClassList = async () => {
  loading.value = true;

  const response = await InventoryGoods.getGoodsClassList({});

  if (response && !response.error && response.data) {
    const rawData = Array.isArray(response.data) ? response.data : [];
    classList.value = processClassData(rawData);
  } else {
    classList.value = [];
  }

  loading.value = false;
};

// 生命周期
onMounted(() => {
  fetchClassList();
});
</script>

<template>
  <div style="height: 100%" class="text-13px">
    <!-- 顶部工具栏 -->
    <div class="flex p-3 bg-white mb-2 rounded">
      <NButton
        v-if="canAdd"
        type="primary"
        size="small"
        class="h-32px px-12px"
        @click="handleAddNew"
      >
        <template #icon>
          <SvgIcon icon="ant-design:plus-outlined" class="w-14px h-14px" />
        </template>
        添加一级分类
      </NButton>

      <div v-if="!canAdd" class="text-gray-500">
        暂无分类管理权限
      </div>
    </div>

    <!-- 表格容器 - 统一滚动容器 -->
    <div class="bg-white rounded border border-gray-200" style="height: calc(100% - 60px); width: 100%">
      <div class="table-wrapper" style="height: 100%; overflow-y: auto; overflow-x: hidden">
        <!-- 表格头部 - 使用sticky定位 -->
        <div class="table-header bg-gray-50 border-b border-gray-200 px-0">
          <div class="flex items-center text-12px font-medium text-gray-700 h-40px">
            <div class="w-50px flex items-center justify-center border-r border-gray-200 h-full"></div> <!-- 拖拽手柄列 -->
            <div class="table-category-col border-r border-gray-200 h-full flex items-center pl-3 pr-3">
              <div class="w-16px mr-2"></div>
              <div>分类</div>
            </div>
            <div class="w-180px px-3 border-r border-gray-200 h-full flex items-center">创建时间</div>
            <div class="w-250px px-3 h-full flex items-center justify-end">操作</div>
          </div>
        </div>

        <!-- 表格内容 -->
        <div class="table-body">
        <div v-if="loading" class="text-center py-12 text-gray-500">
          加载中...
        </div>

        <div v-else-if="classList.length === 0" class="text-center py-12 text-gray-500">
          暂无分类数据
        </div>

        <Draggable
          v-else
          v-model="classList"
          :disabled="!canModify"
          handle=".drag-handle"
          ghost-class="drag-ghost"
          chosen-class="drag-chosen"
          drag-class="drag-drag"
          @end="handleDragEnd"
          item-key="objectId"
          class="draggable-container"
        >
          <template v-for="(record, index) in classList" :key="`parent-${record.objectId}`">
            <!-- 父分类行 -->
            <div
              class="table-row flex items-center border-b border-gray-100 hover:bg-blue-50 text-12px h-36px"
            >
              <!-- 拖拽手柄列 -->
              <div class="w-50px flex items-center justify-center border-r border-gray-200 h-full">
                <div
                  v-if="canModify && !record.goodClassObjectId"
                  class="drag-handle cursor-move text-gray-400 hover:text-blue-600 flex items-center justify-center p-1"
                  title="拖拽排序"
                >
                  <SvgIcon icon="ant-design:holder-outlined" class="w-16px h-16px" />
                </div>
              </div>

              <!-- 分类名称列 -->
              <div class="table-category-col border-r border-gray-200 h-full flex items-center pl-3 pr-3">
                <!-- 展开/折叠图标 -->
                <div
                  v-if="record.children && record.children.length > 0"
                  class="mr-2 cursor-pointer w-16px h-16px flex items-center justify-center text-gray-400 hover:text-blue-600"
                  @click="toggleExpand(record)"
                  :title="record.expanded ? '点击折叠' : '点击展开'"
                >
                  <SvgIcon
                    :icon="record.expanded ? 'ant-design:caret-down-filled' : 'ant-design:caret-right-filled'"
                    class="w-16px h-16px"
                  />
                </div>
                <div v-else class="w-16px mr-2"></div>
                <div class="font-medium text-gray-900">{{ record.content }}</div>
              </div>

              <!-- 创建时间列 -->
              <div class="w-180px px-3 border-r border-gray-200 h-full flex items-center text-gray-600">
                {{ record.createdAt ? formatDate(record.createdAt) : '-' }}
              </div>

              <!-- 操作列 -->
              <div class="w-250px px-3 h-full flex items-center justify-end gap-1">
                <!-- 上移下移按钮（仅一级分类） -->
                <template v-if="!record.goodClassObjectId">
                  <NButton
                    v-if="canModify && index > 0"
                    text
                    size="tiny"
                    class="text-11px px-4px py-1px h-22px"
                    @click="handleMove(index, 1)"
                  >
                    上移
                  </NButton>
                  <NButton
                    v-if="canModify && index < classList.length - 1"
                    text
                    size="tiny"
                    class="text-11px px-4px py-1px h-22px"
                    @click="handleMove(index, -1)"
                  >
                    下移
                  </NButton>
                </template>

                <!-- 添加子类按钮 -->
                <NButton
                  v-if="canAdd && record.key !== undefined"
                  text
                  size="tiny"
                  class="text-11px px-4px py-1px h-22px"
                  @click="handleAddChild(record)"
                >
                  添加子类
                </NButton>

                <!-- 编辑按钮 -->
                <NButton
                  v-if="canModify"
                  text
                  size="tiny"
                  class="text-11px px-4px py-1px h-22px"
                  @click="handleEdit(record)"
                >
                  编辑
                </NButton>

                <!-- 删除按钮 -->
                <NButton
                  v-if="canRemove"
                  text
                  size="tiny"
                  type="error"
                  class="text-11px px-4px py-1px h-22px"
                  @click="handleDelete(record)"
                >
                  删除
                </NButton>
              </div>
            </div>

            <!-- 该父分类的子分类（紧跟在父分类后面） -->
            <template v-if="record.children && record.children.length > 0 && record.expanded">
              <div
                v-for="(child, childIndex) in record.children"
                :key="`child-${child.objectId}`"
                class="table-row flex items-center border-b border-gray-100 hover:bg-blue-50 bg-gray-25 text-12px h-36px"
              >
                <!-- 空的拖拽手柄列 -->
                <div class="w-50px flex items-center justify-center border-r border-gray-200 h-full">
                  <div class="text-gray-300 text-14px flex items-center justify-center">
                    {{ childIndex === record.children.length - 1 ? '└' : '├' }}
                  </div>
                </div>

                <!-- 子分类名称 -->
                <div class="table-category-col border-r border-gray-200 h-full flex items-center pl-3 pr-3">
                  <!-- 与父分类展开图标位置对齐 -->
                  <div class="w-16px mr-2"></div>
                  <div class="text-gray-700">{{ child.content }}</div>
                </div>

                <!-- 子分类创建时间 -->
                <div class="w-180px px-3 border-r border-gray-200 h-full flex items-center text-gray-500">
                  {{ child.createdAt ? formatDate(child.createdAt) : '-' }}
                </div>

                <!-- 子分类操作 -->
                <div class="w-250px px-3 h-full flex items-center justify-end gap-1">
                  <NButton
                    v-if="canModify"
                    text
                    size="tiny"
                    class="text-11px px-4px py-1px h-22px"
                    @click="handleEdit(child)"
                  >
                    编辑
                  </NButton>
                  <NButton
                    v-if="canRemove"
                    text
                    size="tiny"
                    type="error"
                    class="text-11px px-4px py-1px h-22px"
                    @click="handleDelete(child)"
                  >
                    删除
                  </NButton>
                </div>
              </div>
            </template>
          </template>
        </Draggable>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 表格样式 */
.table-header {
  position: sticky;
  top: 0;
  background: #fafafa;
  z-index: 10;
  box-shadow: 0 1px 0 rgba(0, 0, 0, 0.06);
}

.table-row {
  transition: all 0.15s ease;
  border-left: none;
  border-right: none;
  background: white;
}

.table-row:hover {
  background-color: #f0f9ff !important;
}

.table-row:last-child {
  border-bottom: none;
}

.draggable-container {
  min-height: 0;
}

/* 按钮样式优化 */
:deep(.n-button--text-type) {
  padding: 1px 4px !important;
  height: 22px !important;
  font-size: 11px !important;
  min-height: 22px !important;
  border-radius: 2px !important;
}

:deep(.n-button--text-type:hover) {
  background-color: rgba(24, 144, 255, 0.08) !important;
}

:deep(.n-button--text-type.n-button--error-type:hover) {
  background-color: rgba(245, 63, 63, 0.08) !important;
}

/* 拖拽手柄样式 */
.drag-handle {
  transition: all 0.2s ease;
  user-select: none;
  border-radius: 3px;
  width: 20px;
  height: 20px;
}

.drag-handle:hover {
  transform: scale(1.05);
  color: #1890ff !important;
  background-color: rgba(24, 144, 255, 0.1);
}

.drag-handle:active {
  transform: scale(0.95);
}

/* VueDraggableNext 拖拽状态样式 */
.drag-ghost {
  opacity: 0.6 !important;
  background: rgba(24, 144, 255, 0.08) !important;
  transform: rotate(1deg);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
}

.drag-chosen {
  background: rgba(24, 144, 255, 0.05) !important;
  box-shadow: 0 0 0 1px #1890ff !important;
}

.drag-drag {
  opacity: 0.9 !important;
  transform: rotate(1deg);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15) !important;
  background: white !important;
}

/* 固定宽度类 */
.w-50px {
  width: 50px;
  flex-shrink: 0;
  min-width: 50px;
}

.w-180px {
  width: 180px;
  flex-shrink: 0;
  min-width: 180px;
}

.w-250px {
  width: 250px;
  flex-shrink: 0;
  min-width: 250px;
}

.min-w-200px {
  min-width: 200px;
}

.h-40px {
  height: 40px;
}

.h-36px {
  height: 36px;
}

.h-22px {
  height: 22px;
}

/* 禁用文本选择 */
.draggable-container {
  user-select: none;
}

/* 表格行样式修复 */
.table-row.flex {
  display: flex !important;
}

/* 空状态样式 */
.text-center {
  color: #999;
  font-size: 13px;
}

/* 子分类特殊背景 */
.bg-gray-25 {
  background-color: #fafafa;
}

/* 分类列统一宽度 */
.table-category-col {
  flex: 1;
  min-width: 200px;
}
</style>
